<?php

namespace app\common\model\xiluedu;

use think\Exception;
use think\Model;
use function fast\array_get;


class TopicForum extends Model
{

    

    

    // 表名
    protected $name = 'xiluedu_topic_forum';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [
        'status_text',
        'hot_status_text',
        'check_status_text',
        'createtime_text'
    ];

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }

    public function getHotStatusList()
    {
        return ['0' => __('Hot_status 0'), '1' => __('Hot_status 1')];
    }

    public function getCheckStatusList()
    {
        return ['1' => __('Check_status 1'), '2' => __('Check_status 2'), '3' => __('Check_status 3')];
    }

    public function getImagesAttr($value,$data){
        $images = [];
        if($value && is_string($value)){
            $images_array = explode(',',$value);
            foreach ($images_array as $image){
                $images[] = cdnurl($image,true);
            }
        }
        return implode(',',$images);
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getHotStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['hot_status']) ? $data['hot_status'] : '');
        $list = $this->getHotStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCheckStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $list = $this->getCheckStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value,$data){
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    #发帖人信息
    public function user(){
        return $this->belongsTo('\app\common\model\User','user_id');
    }
    #话题
    public function topic(){
        return $this->belongsTo('Topic','topic_id');
    }

    #关注
    public function isFocus(){
        return $this->hasMany(UserFocus::class,'focus_user_id','user_id');
    }

    #点赞
    public function isFav(){
        return $this->hasMany(UserFavourite::class,'favourite_id','id');
    }

    /**
     * 添加帖子
     */
    public static function add($params,$user_id){

        $params['user_id'] = $user_id;

        if(isset($params['images'])){
            $params['images'] = is_array($params['images']) ? implode(',',$params['images']) : $params['images'];
        }

        $validate = new \app\admin\validate\xiluedu\TopicForum;
        if(!$validate->check($params)){
            throw new Exception($validate->getError());
        }
        $result = self::create($params);
        $forumCount = TopicForum::where('topic_id', $params['topic_id'])->count();
        Topic::where('id', $params['topic_id'])->update(['forum_count' => $forumCount]);
        return $result;
    }


    /**
     * 帖子列表
     * @param $params
     * @param bool $hot
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function lists($params,$hot=false,$user_ids=[],$user_id=NULL,$type=""){
        $query = self::with(['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },
            'topic'=>function($query){
            $query->withField(['id','name','image','description','forum_count']);
        }])
            ->withCount(['isFocus'=>function($query) use($user_id){
                $query->where('user_id',$user_id);
            },'isFav'=>function($query) use($user_id){
                $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
            }])

            ->field("*");

            if(!$type || $type != 'my_forum'){
                $query->where('status','1')->whereIn("check_status", ['2']);
            }

        //关注的帖子
        if($user_ids){
            $query->whereIn('user_id',$user_ids)
                ->order('updatetime','desc');
        }
        //热门帖子
        if($hot) {
            $query
                //->where('hot_status',1)
                ->order('fav_count desc,updatetime desc');
        }else{
            $query->order('updatetime','desc');
        }
        //话题帖子
        if($topic_id = array_get($params,'topic_id')){
            $query->where('topic_id',$topic_id);
        }
        $pagesize = array_get($params,'pagesize',10);
        $paginator = $query
            ->paginate($pagesize);
        return $paginator;
    }


    public static function delForum($params,$user_id){
        if(!$forum_id = array_get($params,'forum_id')){
            throw new Exception("删除成功");
        }
        $row = self::get($forum_id);
        if(!$row){
            throw new Exception("帖子不存在");
        }
        if($row->user_id != $user_id){
            throw new Exception("无权操作");
        }
        $row->delete();
        return true;
    }

    /**
     * 帖子详情
     */
    public static function detail($forum_id,$user_id){
        $row = static::get($forum_id,['user'=>function($query){
            $query->withField(['id','nickname','avatar']);
        },'topic'=>function($query){
            $query->withField(['id','name']);
        }]);
        if($row){
            #关注
            $row->relationCount($row,['isFocus'=>function($query) use($user_id){
                $query->where('user_id',$user_id);
            }]);
            #点赞
            $row->relationCount($row,['isFav'=>function($query) use($user_id){
                $query->where('user_id',$user_id)->where('favourite_type',UserFavourite::TYPE_FORUM);
            }]);
        }
        return $row;
    }

}
